<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'title',
        'type',
        'description',
        'image',
        'on_sale',
        'rating',
        'sold_count',
        'review_count',
        'price',
        'category_id',
        'long_title',
        'production_date',
        'base_sale',
        'base_recommend',
        'base_share',
        'address',
        'banner'
    ];

    protected $casts = [
        'on_sale' => 'boolean',
        'address' => 'json',
        'banner' => 'array'
    ];

    protected $dates = [
        'production_date'
    ];

    const IS_SALE = 1; //上架
    const NOT_SALE = 0; //未上架

    public static $saleMap = [
        self::IS_SALE => '是',
        self::NOT_SALE => '否',
    ];

    const PRODUCT_NORMAL = 'product_normal';

    // 商品类型
    public static $typeMap = [
        self::PRODUCT_NORMAL => '普通商品',
    ];

    // 关联单品
    public function skus()
    {
        return $this->hasMany(ProductSku::class);
    }

    // 关联栏目
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    // 关联属性
    public function properties()
    {
        return $this->hasMany(ProductProperty::class);
    }

    // 关联标签
    public function productTags()
    {
        return $this->belongsToMany(ProductTag::class, 'products_product_tags');
    }

    // 关联品牌
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

    // 关联供应商
    public function supplier()
    {
        return $this->belongsTo(Supplier::class);
    }

    // 关联优惠券
    public function couponCodes()
    {
        return $this->morphMany(CouponCode::class, "coupon_codeable");
    }

    // 当前商品的关联用户
    public function userFavorite()
    {
        return $this->belongsToMany(User::class, "user_favorite_products")
            ->withTimestamps()
            ->orderBy('created_at', 'desc');
    }

    public function getGroupPropertiesAttribute()
    {
        return $this->properties->groupBy('name')->map(function ($properties) {
            return $properties->pluck('value')->all();
        });
    }
}
